package com.nuatar.meibi;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.HashMap;
import java.util.Map;

import com.nuatar.meibi.pubvar.PhoneMaster;
import com.nuatar.meibi.pubvar.PostMan;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Looper;
import android.telephony.TelephonyManager;

public class CrashHandler implements UncaughtExceptionHandler {
    public static final String TAG = "CrashHandler";
    private static CrashHandler INSTANCE = new CrashHandler();
    private Context mContext;
    private Thread.UncaughtExceptionHandler mDefaultHandler;

    private CrashHandler() {
    }

    public static CrashHandler getInstance() {
        return INSTANCE;
    }

    public void init(Context ctx) {
        mContext = ctx;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
    	new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                new AlertDialog.Builder(mContext).setTitle("提示").setCancelable(false)
                        .setMessage("对不起，程序崩溃了...造成的困扰请您见谅！我们已经记录此错误信息以便修复此问题").setNegativeButton("我知道了", new OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        })
                        .create().show();
                Looper.loop();
            }
        }.start();
        handleException(ex);
        System.exit(0);
    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. 开发者可以根据自己的情况来自定义异常处理逻辑
     * 
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false
     */
    public boolean handleException(Throwable ex) {
        if (ex == null) {
            return true;
        }
        TelephonyManager telephonyManager = (TelephonyManager) mContext
				.getSystemService(Context.TELEPHONY_SERVICE);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ex.printStackTrace(new PrintStream(baos));
        try {
			baos.close();
			 String info=baos.toString();
		        PackageManager pm = mContext.getPackageManager();  
		        PackageInfo pi;
		        pi = pm.getPackageInfo(mContext.getPackageName(), 0);
		       
				String imei = PhoneMaster.getMD5Str(telephonyManager.getDeviceId());
		        Map<String, String> params=new HashMap<String, String>();
				params.put("info","MMK-ER_"+imei+"_"+pi.versionCode+"_"+pi.versionName+":"+ info);
				String result=PostMan.submitPostData(params, "UTF-8","action=ErrorLog");
				if(result.equals("OK")){
					return true;
				}else{
					return false;
				}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}  
        
        
    }
}